using System;
using System.IO;
using System.Windows.Forms;
using System.Windows.Input;
using ScriptEase.Shell.Controls;



namespace ScriptEase.Shell.Commands
{
    internal class ProjectNewCommand : ICommand
    {
        private readonly ShellViewModel _viewViewModel;



        public ProjectNewCommand(ShellViewModel viewViewModel)
        {
            _viewViewModel = viewViewModel;
        }



        public void Execute(object view)
        {
            string mostRecentProjectName = MruList.Current.MostRecent;
            string dir =
              mostRecentProjectName != null && Directory.Exists(Path.GetDirectoryName(mostRecentProjectName))
                   ? Path.GetDirectoryName(mostRecentProjectName) : Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            SaveFileDialog d = new SaveFileDialog
            {
                CheckFileExists = false,
                DefaultExt = ".seproj",
                Filter = @"ScriptEase Project|*.seproj" + "|All files (*.*)|*.*",
                Title = @"ScriptEase Project",
                RestoreDirectory = true,
                InitialDirectory = dir,
                AddExtension = true,
                AutoUpgradeEnabled = true,
                ValidateNames = true
            };
            DialogResult result = d.ShowDialog(view as Form);
            if (result != DialogResult.OK) return;


            ProjectConfigurationEditor e = new ProjectConfigurationEditor();
            e.SetConfig(Project.NewProject());

            result = e.ShowDialog(view as Form);
            if (result == DialogResult.OK)
            {
                ProjectConfiguration pc = new ProjectConfiguration();
                e.GetConfig(pc);
                Project.SaveToFile(d.FileName, pc);
                _viewViewModel.CloseProject();
                _viewViewModel.OpenProject(d.FileName);
            }
        }



        public bool CanExecute(object parameter)
        {
            return _viewViewModel.ProjectLoadStatus != ProjectStatus.Connecting;
        }



        public event EventHandler CanExecuteChanged;
    }
}